package com.chukun.spring.dependency.injection;

import com.chunkun.ioc.domain.User;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.Collection;

/**
 * {@link org.springframework.beans.factory.ObjectProvider} 实现延迟依赖注入
 * @author chukun
 */
public class LazyAnnotationDependencyInjectionDemo {

    @Autowired
    @Qualifier
    private ObjectProvider<User> userObjectProvider;

    @Autowired
    private ObjectProvider<Collection<User>> usersObjectProvider;

    public static void main(String[] args) {

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

        // 注册 Configuration Class（配置类） -> Spring Bean
        context.register(LazyAnnotationDependencyInjectionDemo.class);

        XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(context);

        String xmlResourcePath = "classpath:/META-INF/dependency-lookup-context.xml";
        // 加载 XML 资源，解析并且生成 BeanDefinition
        beanDefinitionReader.loadBeanDefinitions(xmlResourcePath);

        // 启动 Spring 应用上下文
        context.refresh();

        // 依赖查找 QualifierAnnotationDependencyInjectionDemo Bean
        LazyAnnotationDependencyInjectionDemo demo = context.getBean(LazyAnnotationDependencyInjectionDemo.class);

        System.out.println("=======================================");
        System.out.println("demo.userObjectProvider = " + demo.userObjectProvider.getObject());
        System.out.println("=======================================");
        System.out.println("demo.usersObjectProvider = " + demo.usersObjectProvider.getObject());
        System.out.println("=======================================");
        demo.userObjectProvider.forEach(System.out::println);

        // 显示地关闭 Spring 应用上下文
        context.close();
    }
}
